package com.feng.gaoerfu.view;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.Checkable;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.feng.gaoerfu.R;

/**
 * @time 2017/8/9 0009 19:52
 */
public class FrameLayoutCheckable extends FrameLayout implements Checkable {
    private boolean mChecked = false;
    private TextView mTvName;
    private TextView mTvNum;
    private LinearLayout mParent;

    public FrameLayoutCheckable(Context context) {
        super(context);
    }


    public FrameLayoutCheckable(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    private void init() {
        mTvName = (TextView) getChildAt(0);
        mTvNum = (TextView) getChildAt(1);
    }

    @Override
    public void setChecked(boolean checked) {
        mChecked = checked;
        init();
        if (mChecked) {
            setBackgroundColor(getResources().getColor(R.color.blue));
            mTvName.setTextColor(getResources().getColor(R.color.white));
            mTvNum.setTextColor(getResources().getColor(R.color.white));
        } else {
            setBackgroundColor(getResources().getColor(R.color.white));
            mTvName.setTextColor(getResources().getColor(R.color.text_gray));
            mTvNum.setTextColor(getResources().getColor(R.color.text_gray));
        }
    }

    @Override
    public boolean isChecked() {
        return mChecked;
    }

    public static final String TAG = "FrameLayoutCheckable";

    @Override
    public void toggle() {
        //如果没有选中就选中
        if (!mChecked) {
            setChecked(true);
            //本控件选中的同时其他控件都置为未选中
            mParent = (LinearLayout) getParent();
            int child = mParent.indexOfChild(this);
            int childCount = mParent.getChildCount();
            Log.d(TAG, "child = " + child + ",childCount = " + childCount);
            for (int i = 0; i < childCount; i++) {
                if (i != child) {
                    FrameLayoutCheckable childAt = (FrameLayoutCheckable) mParent.getChildAt(i);
                    if (childAt.isChecked()) {
                        childAt.setChecked(false);
                    }
                }
            }
        }
    }
}
